package com.specialtreasure.freightdepot.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.app.core.activity.BaseNewActivity;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.util.KumaToast;
import com.app.core.util.TimeUtils;
import com.app.core.util.UserUtils;
import com.bigkoo.pickerview.TimePickerView;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.model.Address;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.popupwindow.KMSelectCityPW;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import org.simple.eventbus.EventBus;

import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.specialtreasure.freightdepot.R.id.et_name;

/**
 * Created by KUMA on 2017/9/6.
 */

public class AddOrderActivity extends BaseNewActivity {
    public static final String TAG = "AddOrderActivity";
    @BindView(R.id.ll_root)
    LinearLayout ll_root;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_from)
    TextView tvFrom;
    @BindView(R.id.tv_to)
    TextView tvTo;
    @BindView(R.id.et_info)
    EditText etInfo;
    @BindView(et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_number)
    EditText etNumber;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.et_money_tran)
    EditText etMoneyTran;
    @BindView(R.id.et_money_info)
    EditText etMoneyInfo;

    private Address mAddressFrom = new Address();
    private Address mAddressTo = new Address();
    private Date mDate;
    private boolean isSaveAdd;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_add_order);
        ButterKnife.bind(this);
        initTitleBar();
    }

    private void initTitleBar() {
        show(findViewById(R.id.iv_back));
        ((TextView) findViewById(R.id.tv_title)).setText("添加订单");
    }

    @Override
    public String getActiviyName() {
        return TAG;
    }

    public static void open(Context context) {
        Intent i = new Intent(context, AddOrderActivity.class);
        context.startActivity(i);
    }

    @OnClick({R.id.iv_back, R.id.btn_save_add, R.id.btn_save_cancel, R.id.btn_cancel, R.id.tv_from, R.id.tv_to, R.id.tv_date})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_save_add:
                if (isValidate()) {
                    isSaveAdd = false;
                    fetchAdd();
                }
                break;
            case R.id.btn_save_cancel:
                if (isValidate()) {
                    isSaveAdd = true;
                    fetchAdd();
                }
                break;
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.tv_date:
                //时间选择器
                TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        mDate = date;
                        tvDate.setText(TimeUtils.formatOrder(date.getTime()));
                    }
                })
                        //年月日时分秒 的显示与否，不设置则默认全部显示
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setLabel("", "", "", "", "", "")
                        .isCenterLabel(false)
                        .setDividerColor(Color.DKGRAY)
                        .setContentSize(21)
                        .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                        .setDecorView(null)
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
            case R.id.tv_from:
                final KMSelectCityPW pwFrom = new KMSelectCityPW(this);
                pwFrom.setOnResultListener(new KMSelectCityPW.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        mAddressFrom = address;
                        tvFrom.setText(address.city + address.region);
                    }
                });
                pwFrom.showAtBottom(ll_root);
                break;
            case R.id.tv_to:
                KMSelectCityPW pwTo = new KMSelectCityPW(this);
                pwTo.setOnResultListener(new KMSelectCityPW.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        mAddressTo = address;
                        tvTo.setText(address.city + address.region);
                    }
                });
                pwTo.showAtBottom(ll_root);
                break;
        }
    }

    /**
     * 网络请求
     */
    private void fetchAdd() {
        showDialog(Constants.LOADING);
        String url = Constants.HTTP_URL + HttpApi.addOrder;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.addNull("startProvinceAddress", mAddressFrom.province);
        request.addNull("startCityAddress", mAddressFrom.city);
        request.addNull("startCountyAddress", mAddressFrom.region);
        request.addNull("destProvinceAddress", mAddressTo.province);
        request.addNull("destCityAddress", mAddressTo.city);
        request.addNull("destCountyAddress", mAddressTo.region);
        request.addNull("content", etInfo.getText().toString());
        request.addNull("receiverName", etName.getText().toString());
        request.addNull("receiverPhone", etPhone.getText().toString());
        request.addNull("receiverCarNumber", etNumber.getText().toString());
        request.addNull("transCharge", etMoneyTran.getText().toString());
        request.addNull("itemCharge", etMoneyInfo.getText().toString());
        request.addNull("time", mDate.getTime());

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);
        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                BaseModel baseModel = JSON.parseObject(result, BaseModel.class);
                if (baseModel != null) {
                    Integer status = baseModel.getStatus();
                    String msg = baseModel.getMsg();
                    if (status != null && status == 0) {
                        Toast.makeText(mContext, "添加订单成功", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(new BaseModel(), Constants.UPDATEORDER);
                        if (isSaveAdd) {//保存并退出
                            finish();
                        } else {
                            clearText();
                        }
                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });

    }

    private void clearText() {
        mAddressFrom = new Address();
        mAddressTo = new Address();
        mDate = null;
        tvFrom.setText("");
        tvTo.setText("");
        etInfo.setText("");
        etName.setText("");
        etPhone.setText("");
        etNumber.setText("");
        tvDate.setText("");
        etMoneyTran.setText("");
        etMoneyInfo.setText("");
    }

    private boolean isValidate() {
        if (TextUtils.isEmpty(tvFrom.getText().toString())) {
            KumaToast.show(this, "请选择出发地");
            return false;
        }
        if (TextUtils.isEmpty(tvTo.getText().toString())) {
            KumaToast.show(this, "请选择到达地");
            return false;
        }
        if (TextUtils.isEmpty(etInfo.getText().toString())) {
            KumaToast.show(this, "请输入信息内容");
            return false;
        }
        if (TextUtils.isEmpty(etName.getText().toString())) {
            KumaToast.show(this, "请输入接单人姓名");
            return false;
        }
        if (TextUtils.isEmpty(etPhone.getText().toString())) {
            KumaToast.show(this, "请输入接单电话");
            return false;
        }
        if (TextUtils.isEmpty(etNumber.getText().toString())) {
            KumaToast.show(this, "请输入接单车牌号");
            return false;
        }
        if (TextUtils.isEmpty(tvDate.getText().toString())) {
            KumaToast.show(this, "请选择发货日期");
            return false;
        }
        if (TextUtils.isEmpty(etMoneyTran.getText().toString())) {
            KumaToast.show(this, "请输入运费");
            return false;
        }
        if (TextUtils.isEmpty(etMoneyInfo.getText().toString())) {
            KumaToast.show(this, "请输入信息费");
            return false;
        }

        return true;
    }
}
